from machine import UART,Pin
import _thread
import time



recv_buf=""

# Pin(0) 对应的是GPIO0，Pin(1) 对应的是GPIO1
uart = UART(0,baudrate=115200,tx=Pin(0),rx=Pin(1))



def uartSerialRxMonitor():
    recv=""
    print("start listening...")
    while True:
        print("listening msg...")
        time.sleep(1)
        print(uart.any())
        if uart.any():   # 判断是否有数据可以接收,输出接收到消息的长度
            buffer = uart.readline()       # 读取字符串数据
            data = buffer.decode('utf-8')   # 以UTF-8编码格式对buffer字符串进行解码
            print(data)

# 输出如下内容
# listening msg...
# 65
# +MQTTSUBRECV:0,"testtopic/8266",28,{ "msg": "he312e21e1e1llo" }


print("start...")


uart.write('AT+CWMODE=1'+'\r\n')
time.sleep(2)
print("设置STA模式成功!")
uart.write('AT+CWJAP="Xiaomi_22AE","18030068864"'+'\r\n')
time.sleep(10)
print("连接wifi成功!")
uart.write('AT+MQTTUSERCFG=0,1,"123321","emqx","public",0,0,"/mqtt"'+'\r\n')
time.sleep(5)
print("MQTT client配置成功!")
uart.write('AT+MQTTCONN=0,"192.168.31.96",1883,1'+'\r\n')
time.sleep(5)
print("MQTT连接成功!")
uart.write('AT+MQTTSUB=0,"testtopic/8266",1'+'\r\n')
time.sleep(5)
print("订阅topic:testtopic/8266成功!")



_thread.start_new_thread(uartSerialRxMonitor, ())



time.sleep(3600)